package com.dingreading.cloud.soms.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.KitUtil;
import com.dingreading.cloud.common.util.aliyun.OSSClientUtil;
import com.dingreading.cloud.soms.entity.ReaderContest;
import com.dingreading.cloud.soms.service.ReaderContestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

@RefreshScope
@RestController
@RequestMapping(value = "/front/readerContest")
@Api(tags = "导读教学大赛")
public class ReaderContestController {

    @Value("${readerContest.type}")
    private Integer type;
    @Value("${readerContest.auditionBeginDate}")
    private String auditionBeginDate;
    @Value("${readerContest.auditionEndDate}")
    private String auditionEndDate;
    @Value("${readerContest.finalBeginDate}")
    private String finalBeginDate;
    @Value("${readerContest.finalEndDate}")
    private String finalEndDate;

    @Resource
    private ReaderContestService readerContestService;

    @ApiOperation(value = "获取参赛类型和决赛资格")
    @PostMapping(value = "/getTypeAndFinal", produces = "application/json; charset=UTF-8")
    public R<Object> getTypeAndFinal(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName
    ) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", type);
        int finalStatus = 0;
        if (type != null && type.equals(2)) {
            // 是否有决赛的资格
            boolean b = readerContestService.haveFinal(staffUid);
            finalStatus = b ? 1 : 0;
        }
        jsonObject.put("final", finalStatus);
        return R.ok(jsonObject);
    }

    @ApiOperation(value = "获取参赛信息")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "参赛类型 1.海选 2.决赛") @RequestParam(value = "type") Integer type
    ) throws Exception {
        ReaderContest data = readerContestService.getByStaffUidAndType(staffUid, type);
        if (data != null)
            data.setId(null);
        return R.ok(data);
    }

    @ApiOperation(value = "新增/编辑信息")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "uid") @RequestParam(value = "uid", required = false) String uid,
            @ApiParam(value = "参赛类型 1.海选 2.决赛") @RequestParam(value = "type") Integer type,
            @ApiParam(value = "教学文件地址") @RequestParam(value = "fileUrl") String fileUrl,
            @ApiParam(value = "教学文件名称") @RequestParam(value = "fileName") String fileName,
            @ApiParam(value = "课程名称") @RequestParam(value = "lessonName", required = false) String lessonName,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark
    ) throws Exception {
        if (StringUtils.isBlank(storeName))
            return R.fail("请先完善门店的名称");
        if (StringUtils.isBlank(staffName))
            return R.fail("请先完善员工的姓名");
        if (type == null)
            return R.fail("参赛类型错误");

        if (type.equals(1)) {
            // 海选
            if (StringUtils.isBlank(lessonName))
                return R.fail("请选择题目");
            if (validDate(auditionBeginDate, auditionEndDate))
                return R.fail("参赛日期：" + auditionBeginDate + "至" + auditionEndDate);
        } else if (type.equals(2)) {
            // 决赛
            if (validDate(finalBeginDate, finalEndDate))
                return R.fail("参赛日期：" + finalBeginDate + "至" + finalEndDate);
            // 是否有决赛的资格
            boolean b = readerContestService.haveFinal(staffUid);
            if (!b)
                return R.fail("未进入决赛，不能操作");
        } else {
            return R.fail("参赛类型错误");
        }

        ReaderContest data = null;
        String fileUrlOrg = "";
        if (StringUtils.isBlank(uid)) {
            boolean b = readerContestService.existsByStaffUidAndType(staffUid, type);
            if (b)
                return R.fail("已参加，不能重复操作");

            data = new ReaderContest();
            data.setCorpUid(corpUid);
            data.setStoreUid(storeUid);
            data.setStoreName(storeName);
            data.setAddStaffUid(staffUid);
            data.setAddStaffName(staffName);
            data.setUid(KitUtil.getUuid());
            data.setType(type);
            data.setStatus(0);
        } else {
            data = readerContestService.getByUid(uid);
            if (data == null)
                return R.fail("未查询到信息");
            if (data.getStatus().equals(1))
                return R.fail("已通过，不能操作");
            fileUrlOrg = data.getFileUrl();
        }
        data.setLastStaffUid(staffUid);
        data.setLastStaffName(staffName);
        data.setFileUrl(fileUrl);
        data.setFileName(fileName);
        data.setLessonName(lessonName);
        data.setRemark(remark);
        readerContestService.saveOrUpdate(data);

        // 删除阿里云上的文件
        if (StringUtils.isNotBlank(fileUrlOrg) && !fileUrl.equals(fileUrlOrg)) {
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.initOss();
            ossClientUtil.deleteFile(OSSClientUtil.publicBucket, fileUrlOrg);
        }
        return R.ok();
    }

    /**
     * 验证开始和结束日期
     */
    private boolean validDate(String beginDate, String endDate) throws Exception {
        // 活动开始时间和结束时间
        Date bgnDate = DateUtil.parseDate(beginDate);
        Date enDate = DateUtil.parseDate(endDate);
        String today = DateUtil.getNowDateStr();
        Date todayDate = DateUtil.parseDate(today);
        return todayDate.getTime() < bgnDate.getTime() || todayDate.getTime() > enDate.getTime();
    }

}
